package com.house.config;

import com.house.service.CustomUserDetailsService;
import com.house.service.PasswordEncoderimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    //注入要使用的UserDetailsService对象，这里注入的是自定义的CustomUserDetailsService的对象
    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //指定验证和授权用户使用的UserDetailsService对象是哪个
        //并且指定使用的密码加密器
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**","/error/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable();
        http.authorizeRequests()
                .antMatchers("/test","/welcome","/forget","/doforget","/register","/","/doregister","/index","/login","/house/houselist","/api/**").permitAll()
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/admin/**").hasAnyRole("admin")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login")
                .defaultSuccessUrl("/dologin",true)
                .failureUrl("/login").and().logout().logoutUrl("/logout").logoutSuccessUrl("/index");
    }
    @Bean
    public PasswordEncoderimpl passwordEncoder(){
        return new PasswordEncoderimpl();
    }
}
